package likou.jindian;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/12/18 09:35
 */
public class _04_09_2 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> BSTSequences(TreeNode root) {
        if(root==null){
            res.add(new ArrayList<Integer>());
            return res;
        }
        ArrayDeque<TreeNode> level = new ArrayDeque<>();
        ArrayDeque<Integer> path = new ArrayDeque<>();
        level.add(root);
        dfs(level,path);
        return res;
    }

    private void dfs(ArrayDeque<TreeNode> level, ArrayDeque<Integer> path) {
        if (level.size()==0){
            res.add(new ArrayList<>(path));
            return;
        }
        int levelSize = level.size();
        for (int i=0;i<levelSize;i++){
            TreeNode nowNode = level.pollFirst();
            if (nowNode.left!=null){
                level.offerLast(nowNode.left);
            }
            if (nowNode.right!=null){
                level.offerLast(nowNode.right);
            }
            path.offerLast(nowNode.val);
            dfs(level,path);


            if (nowNode.left!=null){
                level.pollLast();
            }
            if (nowNode.right!=null){
                level.pollLast();
            }
            path.pollLast();
            level.offerLast(nowNode);
        }
    }
}